var yahooMapsAvailable = true;
if(typeof(YGeoPoint) == "undefined" || !YGeoPoint) {
    yahooMapsAvailable = false;
}
var MAP_TYPE_COOKIE = "STREET_MAP_TYPE";
var MAP_LAT_COOKIE = "LATITUDE";
var MAP_LONG_COOKIE = "LONGITUDE";

var setCookie = function(/*String*/name, /*String*/value, /*Number?*/days, /*String?*/path, /*String?*/domain, /*boolean?*/secure){
    var expires = -1;
    if((typeof days == "number")&&(days >= 0)){
        var d = new Date();
        d.setTime(d.getTime()+(days*24*60*60*1000));
        expires = d.toGMTString();
    }
    value = escape(value);
    document.cookie = name + "=" + value + ";"
        + (expires != -1 ? " expires=" + expires + ";" : "")
        + (path ? "path=" + path : "")
        + (domain ? "; domain=" + domain : "")
        + (secure ? "; secure" : "");
}

var getCookie = function(/*String*/name, /*String*/defaultValue){
    var idx = document.cookie.lastIndexOf(name+'=');
    if(idx == -1) { return defaultValue; }
    var value = document.cookie.substring(idx+name.length+1);
    var end = value.indexOf(';');
    if(end == -1) { end = value.length; }
    value = value.substring(0, end);
    value = unescape(value);
    return value; //String
}

var createYahooMarker = function(geopoint, geolabel, txt) {
    var myImage = new YImage();
    myImage.src = '<html:themePath/>images/marker.gif';
    myImage.size = new YSize(159, 82);
    myImage.offsetSmartWindow = new YCoordPoint(0,0);
    var marker = new YMarker(geopoint, myImage);
    marker.addLabel(geolabel);
    return marker;
}

var initYahooMap = function(containerName) {
    var mapType = getCookie(MAP_TYPE_COOKIE);
    map = new YMap($(containerName), mapType);
    map.addPanControl();
    map.addZoomLong();
    map.addTypeControl();

    var divs = $(containerName).getElementsByTagName("div");
    for(var i = 0; i < divs.length; i++) {
        Event.observe(divs[i], 'click', function() {
            var mapType = map.getCurrentMapType();
            setCookie(MAP_TYPE_COOKIE, mapType, null, null, null, null);
        });
    }
    return map;
}

var updateElement = function(liElem) {
    var url = liElem.getAttribute("url");
    window.location.href = url;
}

var storeCurrentPos = function(event, location) {
    var yGeoPoint = map.getCenterLatLon();
    var currentLat = yGeoPoint.Lat;
    var currentLong = yGeoPoint.Lon;
    setCookie(MAP_LAT_COOKIE, currentLat, 365, "/", null, null);
    setCookie(MAP_LONG_COOKIE, currentLong, 365, "/", null, null);
}

var trackPos = function() {
    if(typeof(map) != "undefined" && map) {
        YEvent.Capture(map, EventsList.endPan, storeCurrentPos);
        YEvent.Capture(map, EventsList.endAutoPan, storeCurrentPos);
        YEvent.Capture(map, EventsList.MouseUp, storeCurrentPos);
    }
}

var centerMap = function(latitude, longitude) {
    var myPoint = new YGeoPoint(latitude, longitude);
    map.drawZoomAndCenter(myPoint, 4);
    trackPos();
}